package com.zhengshang.security.service;

import com.zhengshang.common.constant.Constants;
import com.zhengshang.common.core.redis.RedisCache;
import com.zhengshang.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author HY
 * @version 1.0.0
 * @ClassName SmsService.java
 * @Description TODO
 * @createTime 2021年03月03日 15:49
 */
@Component
public class SmsService {

    // 短信验证码失效时间
    @Value("${sms.timeout}")
    private int timeout;

    // 令牌秘钥
    @Value("${sms.secret}")
    private String secret;

    @Autowired
    private RedisCache redisCache;

    /**
     * @title 创建验证码(手机)
     * @description
     * @author admin 
     * @updateTime 2021/3/3 17:27 
     * @throws 
     */
    public String createCode(String phone){
//        deleteCode(phone);
        String code = ((int)(Math.random() * 900000) + 100000) + "";
        redisCache.setCacheObject(getCodeKey(phone), code, timeout, TimeUnit.SECONDS);
        return code;
    }

    /**
     * @title 获取验证码(手机)
     * @description 
     * @author admin 
     * @updateTime 2021/3/3 17:27 
     * @throws 
     */
    public String getCode(String phone) {
        return redisCache.getCacheObject(getCodeKey(phone));
    }

    /**
     * @title 获取验证码(手机)
     * @description
     * @author admin
     * @updateTime 2021/3/3 17:27
     * @throws
     */
    public void deleteCode(String phone) {
        if (StringUtils.isNotBlank(getCode(phone))) {
            redisCache.deleteObject(getCodeKey(phone));
        }
    }

    public String getCodeKey(String phone){
        return Constants.APP_VERIFICATION_CODE + phone;
    }

}
